﻿#region USING STATEMENTS
using System;
using Lidgren.Network;
using EclipseLib.Shared;
#endregion

#region CODE BODY
namespace Client
{
    public class ClientSocket
    {
        // Data Members
        private NetClient Client;
        private NetIncomingMessage Msg;

        // Events & Delegates
        public delegate void ReceiveData(NetIncomingMessage Incoming);
        public event ReceiveData OnReceiveData;

        public delegate void ConnectionResponse(bool Connected);
        public event ConnectionResponse OnConnectionResponse;

        // Constructor
        public ClientSocket()
        {
            NetPeerConfiguration Config = new NetPeerConfiguration(Constants.AppIdentifier);
            Config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            Config.ConnectionTimeout = 5f;

            Client = new NetClient(Config);
            Client.Start();
            Client.Socket.Blocking = false;

            Client.DiscoverKnownPeer(Constants.IpAddress, Constants.Port);
        }

        // Methods
        public void Listen()
        {
            while ((Msg = Client.ReadMessage()) != null)
            {
                if (Msg.MessageType == NetIncomingMessageType.DiscoveryResponse)
                    Client.Connect(Msg.SenderEndpoint);

                if (Msg.MessageType == NetIncomingMessageType.Data)
                {
                    if (OnReceiveData != null)
                        OnReceiveData(Msg);
                }
            }
        }
        public void SendData(NetOutgoingMessage Packet)
        {
            Client.SendMessage(Packet, NetDeliveryMethod.ReliableUnordered);
        }
        public void Close()
        {
            Client.Disconnect("Goodbye!");
        }
        public bool IsConnected(bool SendMessageToListeners = false)
        {
            bool Val = (Client.ConnectionStatus == NetConnectionStatus.Connected);

            if (SendMessageToListeners)
                if (OnConnectionResponse != null)
                    OnConnectionResponse(Val);

            return Val;
        }
        public bool DiscoverServer()
        {
            if (IsConnected())
                return true;

            return Client.DiscoverKnownPeer(Constants.IpAddress, Constants.Port);
        }
        public NetOutgoingMessage CreatePacket()
        {
            return Client.CreateMessage();
        }
        public NetOutgoingMessage CreatePacket(int Capacity)
        {
            return Client.CreateMessage(Capacity);
        }
    }
}
#endregion

//////////////////////////////////////////////////////////////////////////////////////////////
// Copyright 2012 Jeffery Thomas Sventora
//////////////////////////////////////////////////////////////////////////////////////////////